package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.json.JSONObject;

//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;


import org.json.JSONArray
import org.json.JSONException;


/**
 *
 * @Title: ApiBPLogin
 * @Description:深圳宝安排水小程序登录接口--外部接口
 * @author: chieh
 * @date 2020-11-08 21:28:00
 *
 */
public class ApiBPLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPLogin.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        log.debug("-------------------------start ApiBPLogin 开始-----------------");

        //String URL = "https://api.weixin.qq.com/sns/jscode2session";
        //String appid = "wxe07ba4dddd1aeeec";
        //String secret = "439ec3757ae10eee269f46d023274270";
        //String grant_type = "authorization_code";

        //获取配置信息
        String URL = getProperty.get("XCX.URL");
        //小程序 appId
        String appid = getProperty.get("XCX.AAPID");
        //小程序 appSecret
        String secret = getProperty.get("XCX.SECRET");
        //授权类型，此处只需填写 authorization_code
        String grant_type = getProperty.get("XCX.GRANTTYPE");

        long startTime = System.currentTimeMillis();
        response.setContentType("application/json;charset=utf-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String reJson = null;
        long endTime = 0;
        String inData = "";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        JSONArray resArray = new JSONArray();
        JSONObject resObject = new JSONObject();
        //try {
        Map<String, String> dealMap = new HashMap<String, String>();

        // 调用处理信息
        //JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
        JSONObject inObject = new JSONObject(inData);
        log.debug("处理前的Json：" + inObject.toString());
        /*
        String aesString = Util.aesEncrypt("1", "55bd38420d354822bdb789284fac4ab3");
        log.debug("手动AES字符串:" + aesString);
        String s1 = AESUtil.aesEncrypt("1", "55bd38420d354822bdb789284fac4ab3");
        log.debug("加密结果=" + s1);
        */
        //openid 排序问题
        JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
        log.debug("jsonArraytemp: " + jsonArraytemp);

        JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
        log.debug(dataObjecttemp);
        String js_codetemp = GetJV(dataObjecttemp, "js_code");
        log.debug("js_code:" + js_codetemp);

        String replaceString = "[{\"js_code\":\"" + js_codetemp + "\"}]";
        log.debug("replaceString:" + replaceString);

        //鉴权加密处理--验证密码
        JSONObject checkJson = signUtil.CheckSign(inObject, replaceString)
        log.debug("checkJson: " + checkJson);

        if (checkJson != null) {
            log.debug("[签名校验异常-返回信息]:" + checkJson);
            endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:" + signUtil.jsonObjectToMap(checkJson) + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            return reJson;
        } else {
            log.debug("[签名校验成功]");
            // 校验成功
            //todo 业务逻辑
        }
        //data
        JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
        log.debug("jsonArray: " + jsonArray);
        String js_code = jsonArray.getJSONObject(0).get("js_code");
        log.debug("js_code: " + js_code);

        if (js_code == null) {
            endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(参数输入异常),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            return reJson;
        }
        String getParam = "appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type;
        String doURL = URL + "?" + getParam;
        //GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String getResult = Util.doHttpGet(doURL, "UTF-8", 100000, 0);
        log.debug("getResult调用结果返回：" + getResult.toString());
        if (getResult != null && getResult.length() > 0) {
            try {
                //JSONObject loginObject = JSONObject.parseObject(getResult, Feature.OrderedField);

                JSONObject loginObject = new JSONObject(getResult);
                /*
                String openid = loginObject.get("openid");
                String session_key = loginObject.get("session_key");
                String unionid = loginObject.get("unionid");
                String errcode = loginObject.get("errcode");
                String errmsg = loginObject.get("errmsg");
                */

                String openid = GetJV(loginObject, "openid");
                String session_key = GetJV(loginObject, "session_key");
                String unionid = GetJV(loginObject, "unionid");
                String errcode = GetJV(loginObject, "errcode");
                String errmsg = GetJV(loginObject, "errmsg");

                // 记录验证结果
                JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String log_SQL = "Insert Into Kh_Minip_Login (Rec_Id, Js_Code, Open_Id, Unionid, Session_Key, Errcode, Errmsg, Createdtime) Values (?, ?, ?, ?, ?, ?, ?, ?)";
                jt.update(log_SQL, KHUtil.getRandomString(36), js_code, openid, unionid, session_key, errcode, errmsg, df.format(new Date()));

                //返回值
                resObject.put("openid", openid);
                resObject.put("session_key", session_key);
                resObject.put("unionid", unionid);
                resObject.put("errcode", errcode);
                resObject.put("errmsg", errmsg);
                resArray.put(resObject);
            } catch (Exception e) {
                resArray = null;
            }
        }
        endTime = System.currentTimeMillis();
        reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"获取的登录接口调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray + "}";

        //} catch (Exception e) {
        //    log.error("接口处理异常" + e.getMessage());
        // 失败返回
        //  reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"获取的登录接口调用处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        // }
        return reJson;

    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        return Rev_Value;
    }
}